package cn.itsource.pet.service.impl;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.*;
import cn.itsource.order.domain.OrderPetAcquisition;
import cn.itsource.order.mapper.OrderPetAcquisitionMapper;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.dto.MsgDto;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /** 寻主消息审核 */
    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        //2.将寻主消息添加到数据库- 如果审核失败 - 修改寻主消息重新审核【shop_id】
        searchMasterMsgMapper.add(msg);
        //3.百度AI智能审核
        Boolean boo1 = BaiduAiUtil.TextCensor(msg.getName() + msg.getTitle());
        Boolean boo2 = BaiduAiUtil.ImgsCensor(msg.getResources());//这个没传，注释了试一下
        //创建日志对象
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(msg.getId());
        //3.1.审核成功
        if (boo1 && boo2){
            //a.修改状态：0 - 1
            msg.setState(1); //审核通过
            //获取寻主消息的地址经纬度
            Point userPoint = DistanceUtils.getPoint(msg.getAddress());
            //使用工具类找到最近的店铺
            Shop shop = DistanceUtils.getNearestShop(userPoint, shopMapper.findAll());
            if (shop != null){
                //b1.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
                msg.setShopId(shop.getId());
            }else { //50公里以内没有店铺
                //b2.没有找到店铺 - 放到寻主池
                msg.setState(3);
                //告诉店铺管理员 - 有新的寻主消息
                Employee employee = employeeMapper.findOne(shop.getAdmin_id());
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请及时处理！");
                System.out.println("你有新的订单，请及时处理！");
            }
            //b3.更新数据库
            searchMasterMsgMapper.update(msg);
            //c.添加审核日志
            log.setState(1);
            log.setNote("审核通过！");
            searchMasterMsgAuditLogMapper.add(log);
        }else {
            //3.2.审核失败
            //SmsUtils.sendSms(user.getPhone(),"审核失败，请修改后重新发布！");
            //a.发送短信给用户告诉他审核失败，修改寻主消息
            System.out.println("审核失败，请修改后重新发布！");
            //删除寻主消息
            searchMasterMsgMapper.del(msg.getId());
            //b.添加审核失败日志
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);
            return AjaxResult.me().setSuccess(false).setMessage("审核失败，请修改后重新发布！");
        }
        return AjaxResult.me();
    }

    /** 待审核 */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    /** 待处理 */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    /** 寻主池 */
    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query) {
        query.setState(3);
        return super.queryPage(query);
    }

    /** 已完成 */
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    /** 拒单 */
    @Override
    public AjaxResult reject(Long id) {
        searchMasterMsgMapper.updateState(id);
        return new AjaxResult();
    }

    /** 接单 */
    @Override
    public AjaxResult accept(MsgDto dto) {
        //校验当前订单是否在处理
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.findByMagId(dto.getMsgId());
        if (orders != null && orders.size() > 0){
            for (OrderPetAcquisition order : orders) {
                if (order != null && order.getState() == 0){
                    throw new BusinessException("订单正在处理中");
                }
            }
        }
        //生成收购订单
        System.out.println(dto);
        System.out.println(dto.getMsgId());
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(dto.getMsgId());
        System.out.println(msg);
        System.out.println("===");
        OrderPetAcquisition Acquisition = msagDto2Order(dto,msg);
        orderPetAcquisitionMapper.add(Acquisition);
        //通知处理人去处理 - 发送短信
        //Employee employee = employeeMapper.findOne(dto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的宠物订单，请及时处理！");
        System.out.println("你有新的宠物订单，请及时处理！");
        return new AjaxResult();
    }

    private OrderPetAcquisition msagDto2Order(MsgDto dto, SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        System.out.println(msg);
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(dto.getNote());
        //三天内没有接单 - 自动取消订单 - 定时器
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 3*24*60*60*1000));
        order.setState(0); // 待处理
        order.setPrice(msg.getPrice());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(dto.getMsgId());
        return order;
    }
}
